# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.auth import login
from auth_backends import SNSBackend
from django.core.cache import cache
from django.http import HttpResponse
import time,re
from urlparse import urlsplit
import datetime


class SNSMiddleware(object):
    def process_request(self, request):
#        for k,v in request.REQUEST.items():
#            print k
#            print request.REQUEST.getlist(k)
#        print request.user.is_authenticated()
#        for k,v in request.session.items():
#            print k,v
#        print request.COOKIES
        assert hasattr(request, 'session'), "The SNSBackend middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
        if 'xn_sig_user' in request.REQUEST:
            request.__class__.on_sns = True
            request.__class__.on_xiaonei = True
            request.__class__.on_51 = False
            
            if not request.user.is_authenticated() or (request.user.uid != request.REQUEST['xn_sig_user']):
                backend = SNSBackend()
                user = backend.authenticate(request)
                if user:
                    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
                    login(request, user)
                    request.session.modified = True
            
        elif '51_sig_user' in request.REQUEST:
            print request.REQUEST['51_sig_user']
            request.__class__.on_sns = True
            request.__class__.on_xiaonei = False
            request.__class__.on_51 = True
            if not request.user.is_authenticated() or (request.user.uid != request.REQUEST['51_sig_user']):
                backend = SNSBackend()
                user = backend.authenticate(request)
                if user:
                    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
                    login(request, user)
                    request.session.modified = True
        else:
            request.__class__.on_sns = False
            request.__class__.on_xiaonei = False
            request.__class__.on_51 = False
        
    def process_response(self, request, response):
        response['P3P'] = 'CP=CAO PSA OUR'
        return response
